import React, { useEffect, useRef, useState } from 'react';
import Taro, { useDidHide, useDidShow, useUnload } from '@tarojs/taro';
import { View, Image, Text, Video } from '@tarojs/components';
import './index.less';
import TitleBar from '@/src/components/titleBar';
import { observer } from 'mobx-react-lite';
import store from '@/src/store';
import LoadingSpinner from '@/src/components/loadingSpinner';
import { showToast, StatusToast } from '@/src/components/statusToast';
import AddTopicPopup from '@/src/components/addTopicPopup';
import RelatePopup from '@/src/components/relatePopup';
import PhotoRecognition from '@/src/components/photoRecognition';
import { uploadFileFun, videoPublishFun } from '@/src/common/method/publishFun';
import { formatNow } from '@/src/common/method/commonFun';
import CommonModal from '@/src/components/commonModal';
import { getNetWorkStatus } from '@/src/common/util/util';
import { netWorkErrorInfo } from '@/src/utils/constants';
import { AtInput } from 'taro-ui';

const MAX_TITLE = 35;
// 100MB
const MAX_VIDEO_BYTES = 100 * 1024 * 1024;

// 端侧压缩阈值：<=10MB 不压缩，>10MB 再压
const NO_COMPRESS_THRESHOLD = 10 * 1024 * 1024;

let ucUserId = '';
let ucLoginPhone = '';

const PublishVedio = () => {
  const { contentCigar, contentCigarCabinet } = store.publishStore;
  const { province, provinceCode, city, cityCode } = store.commonStore;
  const videoContextRef = useRef<any>(null);
  const videoId = 'video';
  // 视频标题
  const [title, setTitle] = useState('');
  // 视频地址
  const [videoUrl, setVideoUrl] = useState(''); // 上传后返回的地址
  // 封面地址
  const [coverUrl, setCoverUrl] = useState(''); // 裁剪后的封面
  // 显示关联产品弹窗
  const [showPopup, setShowPopup] = useState<boolean>(false);
  // 添加话题弹窗
  const [showTopicPopup, setShowTopicPopup] = useState<boolean>(false);
  // 选择的话题列表
  const [contentTopicList, setContentTopicList] = useState<any>([]);
  // 显示识别雪茄页面
  const [showPhotoRecognition, setShowPhotoRecognition] =
    useState<boolean>(false);
  // 保存提示
  const [showSaveFlag, setShowSaveFlag] = useState<boolean>(false);
  // 等待层文字
  const [loadingText, setLoadingText] = useState<string>('');
  // 视频时长（秒）
  const [contentVideoDuration, setContentVideoDuration] = useState<number>(0);
  const [isPlaying, setIsPlaying] = useState(false);

  // 避免 onShow 多次触发重复弹出选择器
  const pickingRef = useRef(false);
  const uploadingRef = useRef(false);
  //  当前“本次进入页面（挂载到卸载）”是否已经自动弹过一次
  const attemptedThisMountRef = useRef(false);
  //  是否正在打开原生相册选择器（部分机型会触发 onShow/onHide）
  const openingPickerRef = useRef(false);

  const saveOnUnloadRef = useRef(true);
  // 上传恢复需要的状态
  const lastLocalPathRef = useRef<string>(''); // 记录最近一次上传的本地路径
  const currentUploadIdRef = useRef<string>(''); // 当前有效上传任务的 id（防止旧任务晚归覆盖）
  const wasUploadingWhenHiddenRef = useRef<boolean>(false); // 进入后台时是否在上传

  // 小文件直传开关与视频元信息，传给后端用于“跳过转码/高质量转码”
  const keepOriginalRef = useRef<boolean>(false);
  const videoMetaRef = useRef<{
    duration?: number;
    width?: number;
    height?: number;
    size?: number;
  }>({});

  useDidShow(() => {
    Taro.onNetworkStatusChange(getNetWorkStatus);
  });

  // 新增：结束回调
  const handleVideoEnded = () => {
    try {
      videoContextRef.current?.stop(); // 停止并回到 0，避免仅 seek 导致音轨继续
    } catch {}
    setIsPlaying(false);
  };

  // 兜底：从本地路径读取视频时长（秒）
  const getDurationFromPath = async (path: string) => {
    try {
      const info: any = await Taro.getVideoInfo({ src: path });
      // wechat 返回单位为秒
      return Math.floor(info?.duration || 0);
    } catch {
      return 0;
    }
  };

  //安全拼接 OSS 截图参数
  const buildOssSnapshotUrl = (url: string, w: number, h: number) => {
    const sep = url.includes('?') ? '&' : '?';
    // 这里时间点仍用 t_1000，按需可外部传入
    return `${url}${sep}x-oss-process=video/snapshot,t_1000,m_fast,f_jpg,w_${w},h_${h}`;
  };

  // 单张上传并安全回填
  const uploadOne = async (localPath: string) => {
    try {
      uploadingRef.current = true;
      lastLocalPathRef.current = localPath;
      const uploadId = `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
      currentUploadIdRef.current = uploadId;

      setLoadingText('上传中...');
      const url: any = await uploadFileFun(localPath, 'file', {
        type: 'wine_internet_community_video',
        keepOriginal: keepOriginalRef.current ? 1 : 0,
        videoMeta: videoMetaRef.current,
      });

      // —— 防“旧任务晚归”覆盖 —— //
      if (currentUploadIdRef.current !== uploadId) return;

      setVideoUrl(url);

      // 根据宽高判断横竖屏，拼接 OSS 截图参数，当作封面
      const vw = Number(videoMetaRef.current?.width || 0);
      const vh = Number(videoMetaRef.current?.height || 0);
      // 缺省认为横屏（避免竖屏误拉伸的概率更小）
      const isPortrait = vh > vw && vh > 0 && vw > 0;
      const w = isPortrait ? 540 : 1029;
      const h = isPortrait ? 1029 : 540;
      const snapshotUrl = buildOssSnapshotUrl(url, w, h);
      setCoverUrl(snapshotUrl); // 用第一帧（带合适宽高）

      console.log('[upload] done ->', url, ' snapshot ->', snapshotUrl);
    } catch (err) {
      console.error('[upload] failed:', err);
      showToast('视频上传失败，请重试');
      throw err;
    } finally {
      if (currentUploadIdRef.current) {
        uploadingRef.current = false;
        setLoadingText('');
      }
    }
  };

  // 压缩参数配置
  const buildCompressOption = (
    finalPath: string,
    meta?: { width?: number; height?: number }
  ) => {
    const h = meta?.height || 1080;
    let resolution: '480P' | '720P' | '1080P' = '720P';
    let bitrate = 2500; // kbps
    const fps = 30;

    if (h <= 540) {
      resolution = '480P';
      bitrate = 1500;
    } else if (h <= 1080) {
      resolution = '720P';
      bitrate = 2500;
    } else {
      resolution = '1080P';
      bitrate = 4500;
    }

    return {
      src: finalPath,
      quality: 'high' as const,
      bitrate,
      fps,
      resolution,
    };
  };

  // 公共流程 - 仅相册选视频 → 判断大小 → 按需压缩 → 上传
  const pickVideoFlow = async () => {
    try {
      if (pickingRef.current || uploadingRef.current) return;
      pickingRef.current = true;
      openingPickerRef.current = true;
      await new Promise((r) => setTimeout(r, 60));

      // 1) 一律拿原片
      const v = await Taro.chooseVideo({
        sourceType: ['album'],
        compressed: false,
      });
      if (!v?.tempFilePath) return;
      setLoadingText('上传中...');
      let finalPath = v.tempFilePath;

      // 2) 拿原片信息
      let info: any = await Taro.getFileInfo({ filePath: finalPath });
      let durationSec =
        Math.round(v.duration || 0) || (await getDurationFromPath(finalPath));
      setContentVideoDuration(durationSec);

      try {
        const meta: any = await Taro.getVideoInfo({ src: finalPath });
        videoMetaRef.current = {
          duration: Math.floor(meta?.duration || durationSec || 0),
          width: meta?.width,
          height: meta?.height,
          size: info?.size,
        };
      } catch {
        videoMetaRef.current = { duration: durationSec, size: info?.size };
      }

      // 3) ≤10MB：不压，直接上传
      if (info.size <= NO_COMPRESS_THRESHOLD) {
        keepOriginalRef.current = true;
        await uploadOne(finalPath);
        return;
      }

      // 4) >10MB：先压再判（两段式关键）
      setLoadingText('压缩中...');
      const opt: any = buildCompressOption(finalPath, {
        width: videoMetaRef.current.width,
        height: videoMetaRef.current.height,
      });
      try {
        const cv: any = await Taro.compressVideo(opt);
        if (cv?.tempFilePath) {
          finalPath = cv.tempFilePath;
          info = await Taro.getFileInfo({ filePath: finalPath });

          // 刷新 meta（可选）
          try {
            const meta2: any = await Taro.getVideoInfo({ src: finalPath });
            videoMetaRef.current = {
              duration: Math.floor(meta2?.duration || durationSec || 0),
              width: meta2?.width,
              height: meta2?.height,
              size: info?.size,
            };
          } catch {
            videoMetaRef.current.size = info?.size;
          }
        }
      } catch (e) {
        console.warn('compressVideo 失败，回退用原片尝试上传：', e);
        // 若产品不允许原片>100MB，则继续按下一步判断会拦截
      } finally {
        setLoadingText('上传中...');
      }

      // 5) 最终体积判定（压完也必须 ≤100MB）
      if (info.size > MAX_VIDEO_BYTES) {
        showToast('视频过大，压缩后仍超过 100MB', '', 2);
        return;
      }

      keepOriginalRef.current = false; // 这次是压缩后的视频
      await uploadOne(finalPath);
    } catch (e: any) {
      const msg = String(e?.errMsg || '');
      if (msg.includes('cancel')) {
        /* 用户取消，本次不再打扰 */
      } else if (/auth|permission/i.test(msg)) {
        Taro.showModal({
          title: '无法打开相册',
          content: '请在系统设置中允许微信访问相册',
          confirmText: '知道了',
          showCancel: false,
        });
      } else {
        console.error('chooseVideo error:', e);
        showToast('选择视频失败，请重试');
      }
    } finally {
      pickingRef.current = false;
      openingPickerRef.current = false;
      uploadingRef.current = false;
      setLoadingText('');
    }
  };

  // 选择视频
  const chooseVideo = async () => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }

    // 如果标志位卡死（典型：上传被系统中断，loadingText 已空但 uploadingRef 还在）
    if (uploadingRef.current && !loadingText) {
      uploadingRef.current = false;
    }

    // 正在上传中，给用户“强制重新选择”的能力
    if (pickingRef.current || uploadingRef.current) {
      const { confirm } = await Taro.showModal({
        title: '上传进行中',
        content: '检测到当前有上传在进行，是否取消并重新选择视频？',
        confirmText: '重新选择',
        cancelText: '继续等待',
      });
      if (!confirm) return;

      // 逻辑放弃旧任务（若后端返回也会被 uploadId 防抖）
      currentUploadIdRef.current = '';
      uploadingRef.current = false;
      setLoadingText('');
    }

    // 正常进入选择流程
    pickVideoFlow();
  };

  // 当用户在弹窗中选中话题时调用
  const handleTopicSelect = (topic: any) => {
    setContentTopicList((prev: any) => {
      // 已存在则直接返回
      if (prev.some((t: any) => t.id === topic.id)) {
        showToast('该话题已添加');
        return prev;
      }
      // 超过上限
      if (prev.length >= 5) {
        showToast('最多添加 5 个话题');
        return prev;
      }
      return [...prev, topic];
    });
    setShowTopicPopup(false);
  };

  // 删除关联雪茄
  const deleteRelateCiga = () => {
    //判断网络状态
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    store.publishStore.setContentCigar(null);
  };
  // 删除关联雪茄柜
  const deleteRelateCigaCabinet = () => {
    //判断网络状态
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    store.publishStore.setContentCigarCabinet(null);
  };

  // 点击拍照识别的返回事件
  const onBackClickFun = () => {
    setShowPhotoRecognition(false);
  };

  // 选择封面
  const chooseCover = async () => {
    //判断网络状态
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    //判断如果没有上传视频，则不可修改封面
    if (!videoUrl) {
      Taro.showToast({ title: '请先上传视频', icon: 'none' });
      return;
    }
    const res = await Taro.chooseImage({ count: 1, sourceType: ['album'] });
    const path = res?.tempFilePaths?.[0];
    if (!path) return;

    // 这里用 16:9，可按需换成 1（正方形）或 4/3 等
    const ratio = 16 / 9;

    Taro.navigateTo({
      url: `/subPagesAccount/cropper/index?ratio=${ratio}`,
      events: {
        done: async ({ tempFilePath }) => {
          try {
            const url: any = await uploadFileFun(tempFilePath, 'file', {
              type: 'wine_internet_community_video',
            });
            setCoverUrl(url);
          } catch (e) {
            showToast('封面上传失败，请重试');
          }
        },
      },
      success(nav) {
        // 把原图路径发给裁剪页
        nav.eventChannel.emit('init', { src: path });
      },
    });
  };

  // 放在组件内部其它函数旁边
  const resetVideoState = () => {
    try {
      videoContextRef.current?.stop();
    } catch {}
    setIsPlaying(false);
    setVideoUrl('');
    setCoverUrl('');
    setContentVideoDuration(0);

    // 清理上传相关的“续传/卡死”信息
    lastLocalPathRef.current = '';
    keepOriginalRef.current = false;
    videoMetaRef.current = {};
    currentUploadIdRef.current = '';
  };

  const deleteVedio = async () => {
    if (!videoUrl) return;

    // 如果正在上传，先询问是否强制取消并删除
    if (uploadingRef.current) {
      const { confirm } = await Taro.showModal({
        title: '正在上传',
        content: '确定要取消当前上传并删除已选择的视频吗？',
        confirmText: '删除',
        cancelText: '继续上传',
      });
      if (!confirm) return;
    }

    // 取消上传状态与 loading
    uploadingRef.current = false;
    setLoadingText('');

    // 清空本地状态
    resetVideoState();

    // 若有草稿，顺便把草稿里的视频与封面清掉，避免下次进来又被恢复
    const localUserId = String(Taro.getStorageSync('userId') ?? '').trim();
    const draftKey = `publishVideo-${localUserId}`;
    const info = Taro.getStorageSync(draftKey);
    if (info) {
      try {
        const json = JSON.parse(info);
        json.contentVideo = '';
        json.contentImgUrl = [''];
        json.contentVideoDuration = 0;
        Taro.setStorageSync(draftKey, JSON.stringify(json));
      } catch {}
    }

    Taro.showToast({ title: '已删除视频', icon: 'none' });
  };

  // 组成提交信息
  const getDataFun = () => {
    return {
      title,
      contentVideo: videoUrl,
      contentImgUrl: [coverUrl],
      contentTopicList,
      contentCigar,
      contentCigarCabinet,
      contentVideoDuration,
    };
  };

  // 保存草稿
  const okClickFun = () => {
    //判断网络状态
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    const json = getDataFun();
    Taro.setStorageSync(`publishVideo-${ucUserId}`, JSON.stringify(json));
    saveOnUnloadRef.current = false;
    Taro.navigateBack();
  };

  // 不保存草稿
  const cancelClickFun = () => {
    //判断网络状态
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    // 发布成功之后删除保存的草稿
    Taro.removeStorageSync(`publishVideo-${ucUserId}`);
    saveOnUnloadRef.current = false;
    Taro.navigateBack();
    deleteRelateCiga();
    deleteRelateCigaCabinet();
  };

  // 取消草稿
  const otherClickFun = () => {
    setShowSaveFlag(false);
  };

  // 返回点击事件
  const backClickFun = () => {
    store.commonStore.setShowTabBar(true);
    try {
      videoContextRef.current?.stop();
    } catch {}
    if (videoUrl || title) {
      setShowSaveFlag(true);
    } else {
      saveOnUnloadRef.current = false;
      Taro.navigateBack();
    }
  };

  // 发布按钮点击事件
  const handlePublish = () => {
    //判断网络状态
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    if (!title) {
      showToast('请添加标题', 'error', 2);
      return;
    } else if (!videoUrl) {
      showToast('请添加视频', 'error', 2);
      return;
    }

    setLoadingText('正在发布...');
    const json = getDataFun();
    const submitTime = formatNow();
    const params: any = {
      ucUserId,
      ucLoginPhone,
      province,
      provinceCode,
      city,
      cityCode,
      submitTime,
      ...json,
      contentKind: 'CIGAR',
      // 把“是否保留原视频”和元信息传给后端（用于跳过/高质量转码）
      keepOriginal: keepOriginalRef.current ? 1 : 0,
      videoMeta: videoMetaRef.current,
    };
    videoPublishFun(params)
      .then((res: any) => {
        setLoadingText('');
        if (res.code === '0') {
          setTimeout(() => {
            // 发布成功之后删除保存的草稿
            Taro.removeStorageSync(`publishVideo-${ucUserId}`);
            saveOnUnloadRef.current = false;
            Taro.navigateBack();
            deleteRelateCiga();
            deleteRelateCigaCabinet();
            store.commonStore.setShowTabBar(true);
          }, 3000);
          showToast('已发布，审核中', 'success', 3);
        } else {
          showToast('发布失败', 'error', 3);
        }
      })
      .catch(() => {
        setLoadingText('');
      });
  };

  // 删除话题点击事件
  const deleteTopic = (id: any) => {
    setContentTopicList((prev: any) => prev.filter((t: any) => t.id !== id));
  };

  //  自动弹逻辑：同一次“页面挂载”只尝试弹一次（没有任何重试/定时器）
  const scheduleAutoOpenOncePerMount = () => {
    if (attemptedThisMountRef.current) return; // 本次挂载已尝试
    if (videoUrl || pickingRef.current || uploadingRef.current) return;

    // 现取 userId 判断草稿（避免 ucUserId 尚未初始化造成误判）
    const localUserId = String(Taro.getStorageSync('userId') ?? '').trim();
    const hasDraft = !!Taro.getStorageSync(`publishVideo-${localUserId}`);
    if (hasDraft) return;

    //  标记为本次挂载已尝试（无论结果如何，都不再在本次挂载里重复）
    attemptedThisMountRef.current = true;

    // 用 nextTick 避免动画期被吞
    Taro.nextTick(() => {
      // 若此刻正处在“系统相册已打开”的中间态（极端机型 onShow/onHide 抖动），也不再触发
      if (openingPickerRef.current) return;
      if (videoUrl || pickingRef.current || uploadingRef.current) return;
      const uidNow = String(Taro.getStorageSync('userId') ?? '').trim();
      if (Taro.getStorageSync(`publishVideo-${uidNow}`)) return;
      pickVideoFlow();
    });
  };

  // iOS 左滑/返回时一定会触发
  useUnload(() => {
    store.commonStore.setShowTabBar(true);
    try {
      videoContextRef.current?.stop();
    } catch {}
    if (!saveOnUnloadRef.current) return;
    const json = getDataFun();
    const has =
      (json.title && json.title.trim()) ||
      (json.contentVideo && json.contentVideo.trim()) ||
      (json.contentImgUrl &&
        json.contentImgUrl.length > 0 &&
        json.contentImgUrl[0] !== '') ||
      (json.contentTopicList && json.contentTopicList.length > 0) ||
      !!json.contentCigar ||
      !!json.contentCigarCabinet;
    if (has) {
      Taro.setStorageSync(`publishVideo-${ucUserId}`, JSON.stringify(json));
    }
  });

  // 进入后台时记录“当时在不在上传”
  useDidHide(() => {
    wasUploadingWhenHiddenRef.current = uploadingRef.current;
    try {
      videoContextRef.current?.stop();
    } catch {}
  });

  useDidShow(async () => {
    // 1) 如果之前在上传
    if (wasUploadingWhenHiddenRef.current) {
      wasUploadingWhenHiddenRef.current = false;

      // a. 标志还在，但 UI 已无 loading（常见于被系统中断后恢复）
      if (uploadingRef.current && !loadingText) {
        // 释放“卡死”的标志位，让按钮能用
        uploadingRef.current = false;
        setLoadingText('');
        Taro.showToast({ title: '上次上传已中断，请重新上传', icon: 'none' });
      }

      // b. 如果没有获得 url、手里有本地路径、且当前不在上传 —— 自动恢复（实质是重新开始）
      if (!uploadingRef.current && !videoUrl && lastLocalPathRef.current) {
        setTimeout(() => {
          // 再次显示 loading 并重启上传
          uploadOne(lastLocalPathRef.current);
        }, 120);
      }
    }

    // 草稿优先恢复（现取 userId），否则安排“同一次挂载只尝试一次”的自动弹
    const localUserId = String(Taro.getStorageSync('userId') ?? '').trim();
    const info = Taro.getStorageSync(`publishVideo-${localUserId}`);
    if (info) {
      const json: any = JSON.parse(info);
      setVideoUrl(json.contentVideo);
      setTitle(json.title);
      setContentTopicList(json.contentTopicList);
      setCoverUrl((json.contentImgUrl && json.contentImgUrl[0]) || '');
      setContentVideoDuration(json.contentVideoDuration || 0);
    } else {
      scheduleAutoOpenOncePerMount(); //  无草稿 → 本次挂载只尝试一次自动弹
    }
  });

  useEffect(() => {
    ucUserId = String(Taro.getStorageSync('userId') ?? '').trim();
    ucLoginPhone = String(Taro.getStorageSync('mobile') ?? '').trim();
    videoContextRef.current = Taro.createVideoContext(videoId);

    //  组件卸载时，下一次进入将重新挂载 → attemptedThisMountRef 将自然重置为 false
    return () => {
      deleteRelateCiga();
      deleteRelateCigaCabinet();
    };
  }, []);
  //关联产品
  const handleRelateProduct = () => {
    //判断网络状态
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    setShowPopup(true);
  };
  //添加话题
  const handleAddTopic = () => {
    //判断网络状态
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    setShowTopicPopup(true);
  };
  return (
    <View
      className="publish-review-page"
      style={{ paddingTop: `${store.commonStore.pageAreaTop}rpx` }}
    >
      {showPhotoRecognition ? (
        <PhotoRecognition
          okClickFun={() => {}}
          showRecord={false}
          onBackClickFun={onBackClickFun}
        ></PhotoRecognition>
      ) : (
        <View className="publish-container">
          {/* 标题区 */}
          <TitleBar
            showLeftBack={true}
            title="发视频"
            onBack={backClickFun}
          ></TitleBar>
          <View className="publish-title">
            <View className="publish" onClick={handlePublish}>
              发布
            </View>
          </View>
          <AtInput
            className="title-input"
            placeholder="给视频添加一个标题吧！ (1~35 字)"
            value={title}
            name="title"
            maxLength={MAX_TITLE}
            onChange={(e: any) => setTitle(e.trim())}
          />
          <View
            className="content-area"
            style={{
              height: `calc(100vh - 210px - ${store.commonStore.pageAreaTop}rpx - ${store.commonStore.safeAreaBottom}rpx)`,
            }}
          >
            {/* 正文区 */}
            <View className="video-container">
              <Video
                id={videoId}
                key={videoUrl} // 只用视频 URL 做 key，避免改封面导致重建
                src={videoUrl}
                poster={coverUrl || undefined}
                controls
                showPlayBtn
                showCenterPlayBtn
                enablePlayGesture
                autoplay={false}
                objectFit="contain"
                className="video-player"
                showProgress={false}
                showFullscreenBtn={false}
                enableProgressGesture={false}
                onPlay={() => setIsPlaying(true)} // 记录播放状态
                onPause={() => setIsPlaying(false)}
                onEnded={handleVideoEnded}
              />
              <View className="video-buttons">
                <Image
                  src="https://file.linkcook.cn/image/wineMiniProgram/home/reupload.png"
                  onClick={chooseVideo}
                  className="reload"
                ></Image>
                <Image
                  src="https://file.linkcook.cn/image/wineMiniProgram/home/modify.png"
                  onClick={chooseCover}
                  className="modify"
                ></Image>
                {!!videoUrl && (
                  <Image
                    src="https://file.linkcook.cn/image/wineMiniProgram/home/delete.png"
                    className="delete-icon"
                    onClick={deleteVedio}
                  />
                )}
              </View>
            </View>
            {contentTopicList.length > 0 && (
              <View className="topic-list">
                {contentTopicList.map((item: any, index: number) => {
                  return (
                    <View className="topic-item" key={index}>
                      <Image
                        src="https://file.linkcook.cn/image/wineMiniProgram/home/topic-delete.png"
                        className="deleteIcon"
                        onClick={() => deleteTopic(item.id)}
                      ></Image>
                      <Text>#{item.topicName}#</Text>
                    </View>
                  );
                })}
              </View>
            )}
            {contentCigar && (
              <View className="topic-container">
                <View className="relation">
                  关联雪茄：
                  <Text className="product">
                    {contentCigar.contentCigarBrand}{' '}
                    {contentCigar.contentCigarZh}
                  </Text>
                </View>
                <Image
                  src="https://file.linkcook.cn/image/wineMiniProgram/home/clear.png"
                  className="deleteRelation"
                  onClick={deleteRelateCiga}
                ></Image>
              </View>
            )}
            {contentCigarCabinet && (
              <View className="topic-container relation-cabinet">
                <View className="relation">
                  关联雪茄柜：
                  <Text className="product">
                    {contentCigarCabinet.contentCigarCabinetZh}{' '}
                    {contentCigarCabinet.contentCigarCabinetBrand}{' '}
                    {contentCigarCabinet.model}
                  </Text>
                </View>
                <Image
                  src="https://file.linkcook.cn/image/wineMiniProgram/home/clear.png"
                  className="deleteRelation"
                  onClick={deleteRelateCigaCabinet}
                ></Image>
              </View>
            )}
          </View>
          <View className="publish-buttons">
            <View onClick={() => handleRelateProduct()}>
              <View className="button-container">
                <Image
                  src="https://file.linkcook.cn/image/wineMiniProgram/home/relationPro.png"
                  className="bt-icon"
                ></Image>
              </View>
              <View className="bt-desc">关联产品</View>
            </View>
            <View
              onClick={() => {
                handleAddTopic();
              }}
            >
              <View className="button-container">
                <Image
                  src="https://file.linkcook.cn/image/wineMiniProgram/home/addTopic.png"
                  className="bt-icon"
                ></Image>
              </View>
              <View className="bt-desc">添加话题</View>
            </View>
          </View>
          <LoadingSpinner text={loadingText} />
          <StatusToast />
          <RelatePopup
            isShow={showPopup}
            onClose={() => {
              setShowPopup(false);
            }}
            takeCigaPhoto={() => {
              Taro.showToast({ title: 'AI识别开发中', icon: 'none' });
              // setShowPhotoRecognition(true);
              // setShowPopup(false);
            }}
          ></RelatePopup>
          <AddTopicPopup
            visible={showTopicPopup}
            selectedTopic={handleTopicSelect}
            onClose={() => {
              setShowTopicPopup(false);
            }}
          ></AddTopicPopup>
          <CommonModal
            visible={showSaveFlag}
            title="是否保存当前修改？"
            okText="保存草稿"
            okClick={okClickFun}
            cancelText="不保存"
            cancelClick={cancelClickFun}
            otherText="取消"
            otherClick={otherClickFun}
          ></CommonModal>
        </View>
      )}
    </View>
  );
};

export default observer(PublishVedio);
